Reduce

The reduce function continously applies a function to a sequence. Like map, reduce has the same genera syntax:

reduce(function, sequence)

Semantically, the initial call of reduce is actually where the difference between map() exists. Reduce takes the first two items from the sequence, and applies function on the items, returning a single item. Now, the list is dynamically changed so that the two previous items in the sequence are replaced with a single, combined item.

reduce(function, [item1, item2, item3, item4])
---> [function(item1, item2), item3, item 4]
---> [function(function(item1, item2), item3), item4]
---> [function(function(function(item1, item2), item3) item4)]

The last arrow is the single combined item of all 4 items. Let's take a look at a few examples.

Example 1: Finding the sum of a list.


In [17]:
from functools import reduce

find_my_sum = [5, 3, 19, 48, 2, 31, 29]

def sum_func(x, y):
    return x + y

total = reduce(sum_func, find_my_sum)

In [18]:
print(total)


137

Let's look at how it worked. First, we made a list, and defined the function. After we supplied the arguments, the reduce function spreaded as described above.

1. total = [5, 3, 19, 48, 2, 31, 29]
2. total = [sum_func(5, 3), 19, 48, 2, 31, 29]
3. total = [sum_func(8, 19), 48, 2, 31, 29]
4. total = [sum_func(27, 48), 2, 31, 29]
5. total = [sum_func(75, 2), 31, 29]
6. total = [sum_func(77, 31), 29]
7. total = [sum_func(108, 29)]
8. total = [137]
9. total = 137

Example 2 Creating a sentence out of a list of words.


In [19]:
word_lst = ["hello", "there", "martha", "how", "are", "you", "doing"]
sentence = reduce(lambda x,y: x + " " + y, word_lst)

Here, we used a lambda expressiont unpack two variables (both strings), and then continue to create a sentence as the reduce continously applies the function at hand.

Example 3 Finding the maximum of a sequence.


In [23]:
nums = [5, 5, 39, 29, 48, 98, 23, 48]
max_num = reduce(lambda num1,num2: num1 if num1 > num2 else num2, nums)

In [24]:
print(max_num)


98